import { defineStore } from 'pinia'
import { v4 as uuidv4 } from 'uuid'

export const useCategoryStore = defineStore('categories', {
  state: () => ({
    categories: [],
    loading: false,
    error: null
  }),
  getters: {
    // 获取所有分类
    allCategories: (state) => state.categories,
    
    // 获取特定分类
    getCategoryById: (state) => (id) => {
      return state.categories.find(category => category.id === id) || null
    },
    
    // 获取排序后的分类
    sortedCategories: (state) => {
      return [...state.categories].sort((a, b) => a.order - b.order)
    }
  },
  actions: {
    // 初始化默认分类
    initDefaultCategories() {
      // 只有当没有分类时才初始化默认分类
      if (this.categories.length === 0) {
        const defaultCategories = [
          {
            id: uuidv4(),
            name: '工作',
            color: '#4CAF50', // 绿色
            icon: 'mdi-briefcase-outline',
            createdAt: new Date(),
            updatedAt: new Date(),
            order: 0
          },
          {
            id: uuidv4(),
            name: '学习',
            color: '#2196F3', // 蓝色
            icon: 'mdi-book-open-page-variant-outline',
            createdAt: new Date(),
            updatedAt: new Date(),
            order: 1
          },
          {
            id: uuidv4(),
            name: '生活',
            color: '#FF9800', // 橙色
            icon: 'mdi-home-outline',
            createdAt: new Date(),
            updatedAt: new Date(),
            order: 2
          }
        ]
        
        this.categories = defaultCategories
        this.saveCategories()
      }
    },
    
    // 添加新分类
    addCategory(categoryData) {
      const newCategory = {
        id: uuidv4(),
        name: categoryData.name,
        color: categoryData.color || '#9C27B0', // 默认紫色
        icon: categoryData.icon || 'mdi-label-outline',
        createdAt: new Date(),
        updatedAt: new Date(),
        order: this.categories.length // 新分类放在最后
      }
      
      this.categories.push(newCategory)
      this.saveCategories()
      return newCategory
    },
    
    // 更新分类
    updateCategory(id, updatedData) {
      const categoryIndex = this.categories.findIndex(category => category.id === id)
      
      if (categoryIndex !== -1) {
        this.categories[categoryIndex] = {
          ...this.categories[categoryIndex],
          ...updatedData,
          updatedAt: new Date()
        }
        this.saveCategories()
        return true
      }
      
      return false
    },
    
    // 删除分类
    deleteCategory(id) {
      const categoryIndex = this.categories.findIndex(category => category.id === id)
      
      if (categoryIndex !== -1) {
        this.categories.splice(categoryIndex, 1)
        this.saveCategories()
        return true
      }
      
      return false
    },
    
    // 更新分类顺序
    updateCategoriesOrder(orderedIds) {
      const categoriesMap = {}
      this.categories.forEach(category => {
        categoriesMap[category.id] = category
      })
      
      const orderedCategories = orderedIds.map((id, index) => {
        const category = categoriesMap[id]
        if (category) {
          return {
            ...category,
            order: index
          }
        }
        return null
      }).filter(Boolean)
      
      if (orderedCategories.length === this.categories.length) {
        this.categories = orderedCategories
        this.saveCategories()
        return true
      }
      
      return false
    },
    
    // 加载分类
    async loadCategories() {
      this.loading = true
      this.error = null
      
      try {
        // 这里将来会使用Tauri的文件系统API读取分类数据
        // 暂时使用localStorage模拟
        const categoriesData = localStorage.getItem('todo_categories')
        if (categoriesData) {
          this.categories = JSON.parse(categoriesData)
        } else {
          this.initDefaultCategories()
        }
      } catch (err) {
        console.error('加载分类失败:', err)
        this.error = '加载分类失败'
      } finally {
        this.loading = false
      }
    },
    
    // 保存分类
    saveCategories() {
      try {
        // 这里将来会使用Tauri的文件系统API保存分类数据
        // 暂时使用localStorage模拟
        localStorage.setItem('todo_categories', JSON.stringify(this.categories))
      } catch (err) {
        console.error('保存分类失败:', err)
        this.error = '保存分类失败'
      }
    }
  }
}) 